package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.entity.Game;
import com.example.demo.entity.User;
import com.example.demo.service.GameService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.List;

import static com.example.demo.util.Constants.*;

/**
 * @author shenrui
 * @date 2021/9/19
 * @description 设置创建Game，输出答案，显示记录
 */
@Controller
public class GameController {
    @Resource
    GameService gameService;

    /**
     *@description 跳转到游戏界面，并生成游戏
     * @return String
     */
    @GetMapping("/to_user_game")
    public String userGame(HttpSession session) {
        long[] heightList = gameService.createGame();
        long maxVolume = gameService.answerGame(heightList);
        StringBuilder heightString = new StringBuilder();
        for(int i = 0;i < GAME_AMOUNT;i++) {
            heightString.append(heightList[i]+" ");
        }
        session.setAttribute("maxVolume",maxVolume);
        session.setAttribute("heightString",heightString);
        return "redirect:user_game";

    }
    /**
     *@description 显示游戏结果
     * @return String
     */
    @PostMapping("/to_game_submit")
    public String gameResult(@RequestParam(value = "userAnswer") Long userAnswer, HttpSession session) {
        Game game = new Game();
        game.setGameRecord(((StringBuilder)session.getAttribute("heightString")).toString());
        game.setGameAnswer(((Long)session.getAttribute("maxVolume")));
        game.setUsrAnswer(userAnswer);
        game.setUsrId(((User)session.getAttribute("userLogin")).getUsrId());
        if(((Long)session.getAttribute("maxVolume")).equals(userAnswer)) {
            session.setAttribute("gameMsg","回答正确");
        } else {
            session.setAttribute("gameMsg","回答错误");
        }
        if(gameService.save(game)) {
            return "user/game_result";
        } else {
            session.setAttribute("gameMsg","提交失败");
            return "user/game_result";
        }
    }

    /**
     *@description 查看游戏记录
     * @return String
     */
    @GetMapping("/to_game_record")
    public String gameRecord(HttpSession session) {
        List<Game> gameList = gameService.list(new LambdaQueryWrapper<Game>().eq(Game::getUsrId, ((User)session.getAttribute("userLogin")).getUsrId()));
        session.setAttribute("gameList", gameList);
        return "user/game_list";
    }
}
